package com.liuyjy.redis.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author liuyjy
 * @Date 2025/1/2 16:13
 * @Description: 公共方法
 **/
@Slf4j
public class Utils {


    /**
     * 获取key
     *
     * @param k    主键
     * @param subK 子键
     * @return key
     */
    public static String getKey(String k, String subK) {
        if (StringUtils.isBlank(k) && StringUtils.isBlank(subK)) {
            throw new IllegalStateException("获取key: key为空");
        }
        if (StringUtils.isBlank(subK)) {
            return k;
        }
        if (StringUtils.isBlank(k)) {
            return subK;
        }
        return k + ":" + subK;
    }

    /**
     * 将实体类对象属性转化为map对象
     *
     * @param t   对象
     * @param <T> 对象类型
     * @return Map
     */
    public static <T> Map<String, Object> beanToMap(T t) {
        if (t == null) {
            return new HashMap<>();
        }
        if (t instanceof Map) {
            return new HashMap<>((Map<String, Object>) t);
        }
        Map<String, Object> map = new HashMap<>();
        if (t instanceof JSONObject) {
            return (JSONObject) t;
        }
        BeanMap beanMap = BeanMap.create(t);
        for (Object key : beanMap.keySet()) {
            map.put(key.toString(), beanMap.get(key));
        }
        return map;
    }

    /**
     * 将map对象中转化为实体类对象
     *
     * @param map   map
     * @param clazz clazz
     * @param <T>   对象类型
     * @return T
     */
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        if (bean instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) bean;
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            @SuppressWarnings("unchecked")
            T jsonObject1 = (T) jsonObject;
            return jsonObject1;
        }
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }
}
